<script setup lang="ts">
import { unitDeptTree } from '@/components/unit/'
import { HrEnumDic, HrItemDic } from '@/config/publicDic'
import { reactive, ref, onMounted } from 'vue'
import { GetItemName } from '@/api/base/dictItem'
import { FormSchema } from '@/components/Form'
import * as deptApi from '@/api/unit/dept'
import { Icon } from '@/components/Icon'
import { useIcon } from '@/hooks/web/useIcon'
import { empChoice } from '@/components/emp/index'
import editDept from './components/editDept.vue'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DeptTree } from '@/api/types/dept'
import { hasPermission } from '@/directives/permission/hasPermi'
import router from '@/router'
const queryParam = ref({
  CompanyId: null,
  QueryKey: null,
  UnitId: null,
  IsUnit: false,
  Status: []
})
const plus = useIcon({ icon: 'ep:plus' })
const drop = useIcon({ icon: 'ep:delete' })
const edit = useIcon({ icon: 'ep:edit' })
const search = ref(null)
const deptTree = ref(null)
let unitId = []
const depts = ref<DeptTree[]>([])
let deptTags = {}
const loading = ref(false)
const handleSearch = (data) => {
  loading.value = true
  queryParam.value.QueryKey = data.QueryKey
  queryParam.value.Status = data.Status
  loadDept()
}
const deptChange = (deptId, e) => {
  loading.value = true
  queryParam.value.CompanyId = e.companyId
  if (deptId.length === 0) {
    queryParam.value.UnitId = null
    queryParam.value.IsUnit = true
    unitId = []
    title.value = e.comName[e.companyId] + '公司-单位列表'
  } else {
    title.value = e.value[0].Name + '-部门列表'
    queryParam.value.IsUnit = false
    queryParam.value.UnitId = deptId[0]
    unitId = deptId
  }
  loadDept()
}
const loadDept = async () => {
  const list = await deptApi.gets(queryParam.value)
  list.forEach((c) => {
    formatRow(c)
  })
  depts.value = list
  loading.value = false
}
const getTag = (tags) => {
  let tag = ''
  tags.forEach((c) => {
    tag = tag + ',' + deptTags[c]
  })
  if (tag.length === 0) {
    return null
  }
  return tag.substring(1)
}
const initDic = async () => {
  deptTags = await GetItemName(HrItemDic.deptTag)
}
const reset = () => {
  initDic()
  queryParam.value.QueryKey = null
  queryParam.value.Status = []
}
const formatRow = (row) => {
  if (row.DeptTag != null) {
    row.DeptTag = getTag(row.DeptTag)
  }
  if (row.LeaderName == null) {
    row.LeaderName = null
  }
  if (row.Children && row.Children.length !== 0) {
    row.Children.forEach((c) => {
      formatRow(c)
    })
  }
}
const editDeptInfo = (row) => {
  parentId = null
  deptId = row.Id
  isUnit = row.IsUnit
  visible.value = true
}
onMounted(reset)

const schema = reactive<FormSchema[]>([
  {
    field: 'QueryKey',
    label: '部门名',
    component: 'Input',
    componentProps: {
      placeholder: '部门名'
    }
  },
  {
    field: 'Status',
    label: '部门状态',
    component: 'EnumItem',
    componentProps: {
      placeholder: '部门状态',
      dicKey: HrEnumDic.deptStatus,
      multiple: true
    }
  }
])

const columns: TableColumn[] = [
  {
    field: 'DeptName',
    label: '全名',
    align: 'left',
    headerAlign: 'center',
    sortable: true
  },
  {
    field: 'ShortName',
    label: '简称',
    headerAlign: 'center',
    sortable: true
  },
  {
    field: 'LeaderName',
    label: '负责人',
    headerAlign: 'center',
    sortable: true,
    sortBy: 'LeaderId',
    slotName: 'leader'
  },
  {
    field: 'IsUnit',
    label: '是否为单位',
    slotName: 'isUnit'
  },
  {
    field: 'Status',
    label: '状态',
    slotName: 'status'
  },
  {
    field: 'DeptTag',
    label: '部门分类',
    align: 'left'
  },
  {
    field: 'action',
    label: '操作',
    align: 'left',
    headerAlign: 'center',
    slotName: 'action'
  }
]
const title = ref('部门列表')
const empVisible = ref<boolean>(false)
let empId: string[]
let empTitle: string = ''
let curRow: DeptTree | null = null
const editLeader = (row: DeptTree) => {
  curRow = row
  empId = row.LeaderId == null ? [] : [row.LeaderId]
  empTitle = '选择' + (row.IsUnit ? '单位' : '部门') + row.DeptName + '负责人'
  empVisible.value = true
}
const setLeader = async (e) => {
  if (curRow != null) {
    const leader = e.user.length === 0 ? null : e.user[0]
    if (leader == null) {
      await deptApi.setLeader(curRow.Id, null)
      curRow.LeaderId = null
      curRow.LeaderName = null
    } else {
      await deptApi.setLeader(curRow.Id, leader.EmpId)
      curRow.LeaderId = leader.EmpId
      curRow.LeaderName = leader.EmpName
    }
  }
}
let isUnit = false
let deptId = null
let parentId: string | null = null
const visible = ref<boolean>(false)
const addUnit = (pid: string | null) => {
  parentId = pid
  isUnit = true
  visible.value = true
}
const addDept = (pid) => {
  parentId = pid
  deptId = null
  isUnit = false
  visible.value = true
}
const closeDept = (isRefresh) => {
  if (!isRefresh) {
    return
  } else if (isUnit === false) {
    loadDept()
  } else if (deptTree.value) {
    deptTree.value.refresh()
  }
}
const submitDrop = async (id, isUnit) => {
  await deptApi.Delete(id)
  ElMessage.success('删除成功!')
  loadDept()
  if (isUnit && deptTree.value) {
    deptTree.value.refresh()
  }
}
const statusChange = async (row, value) => {
  if (value === 1) {
    await deptApi.enable([row.Id])
  } else {
    await deptApi.stop(row.Id)
  }
  row.Status = value
}
const deleteDept = (row) => {
  const title = '确认删除 ' + (row.IsUnit ? '单位' : '部门') + row.DeptName + '?'
  ElMessageBox.confirm(title, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    submitDrop(row.Id, row.IsUnit)
  })
}
const dismissDept = () => {
  router.push({ name: 'deptChange' })
}
</script>
<template>
  <div>
    <leftRightSplit :left-span="4">
      <template #left>
        <ContentWrap title="单位列表">
          <unitDeptTree
            ref="deptTree"
            :status="[]"
            :is-unit="true"
            @load="deptChange"
            @change="deptChange"
          />
        </ContentWrap>
      </template>
      <template #right>
        <ContentWrap :title="title">
          <div class="app-container">
            <Search
              ref="search"
              :schema="schema"
              :model="queryParam"
              :is-col="false"
              layout="inline"
              :showSearch="true"
              button-position="left"
              :search-loading="loading"
              :reset-loading="loading"
              @search="handleSearch"
              @reset="handleSearch"
            >
              <template #opts>
                <BaseButton v-hasPermi="'hr.dept.merge'" type="warning" @click="dismissDept"
                  >解散单位/部门</BaseButton
                >
                <BaseButton v-hasPermi="'add'" type="success" @click="addUnit(null)"
                  >新增单位</BaseButton
                >
                <BaseButton
                  v-hasPermi="'add'"
                  v-if="queryParam.UnitId != null"
                  type="primary"
                  @click="addDept(null)"
                  >新增部门</BaseButton
                >
              </template>
            </Search>
          </div>
          <Table
            :columns="columns"
            :data="depts"
            :showAction="true"
            row-key="Id"
            :defaultExpandAll="true"
            :loading="loading"
            :defaultSort="{ prop: 'Id', isDesc: true }"
          >
            <template #action="e">
              <BaseButton
                :icon="plus"
                v-hasPermi="'add'"
                size="small"
                circle
                @click="addDept(e.row.Id)"
              />
              <BaseButton
                v-hasPermi="'delete'"
                v-if="e.row.Status == 0"
                size="small"
                :icon="drop"
                type="danger"
                circle
                @click="deleteDept(e.row)"
              />
              <BaseButton
                v-hasPermi="'set'"
                v-if="e.row.Status == 0 || e.row.Status == 2"
                :icon="edit"
                size="small"
                type="primary"
                circle
                @click="editDeptInfo(e.row)"
              />
            </template>
            <template #isUnit="e">
              <el-tag v-if="e.row.IsUnit">是</el-tag>
              <el-tag v-else type="info">否</el-tag>
            </template>
            <template #leader="e">
              <el-space>
                <span>{{ e.row.LeaderName }}</span>
                <Icon
                  icon="ep:edit"
                  style="cursor: pointer"
                  v-hasPermi="'set'"
                  @click="editLeader(e.row)"
                />
              </el-space>
            </template>
            <template #status="e">
              <el-switch
                v-model="e.row.Status"
                :disabled="hasPermission('set') == false"
                :inactive-value="2"
                :active-value="1"
                @change="(value) => statusChange(e.row, value)"
              />
            </template>
          </Table>
        </ContentWrap>
      </template>
    </leftRightSplit>
    <empChoice
      v-model:visible="empVisible"
      :emp-id="empId"
      :title="empTitle"
      :unit-id="unitId"
      :is-multiple="false"
      @save="setLeader"
    />
    <editDept
      :dept-id="deptId"
      :is-unit="isUnit"
      :unit-id="queryParam.UnitId"
      :parent-id="parentId"
      v-model:visible="visible"
      @close="closeDept"
    />
  </div>
</template>
